#!/bin/bash

if [ $# -lt 1 ]; then
   echo "输入md文件"
   exit 1
fi

filename=${1%.*}
echo "filename ：${filename}"
filePath="./posts/${1}"

# 是否为创建新文档
isnew=false
if [ ! -f "${filename}.bak" ];then
    echo "${filename}.bak don\`t exist!"
    isnew=true
else
    echo "${filename}.bak exist!"
fi
# 新建文章
cd ../
if [ "${isnew}" = "true" ] ; then
    echo "creating ..."
    hexo new ${filename}
else 
    echo "modify ..."
fi

# 创建md原文档临时副本
echo "create md temp file ${filename}.temp ..."
cp ${filePath} ./posts/${filename}.temp

# 替换修改的文件为临时文件
filePath="./posts/${filename}.temp"

# 获取标题时间
title=`cat ${filePath} |grep "#" -m 1|awk '{print $2}'`
tags=""
categories=""
date=""

# 获取当前时间作为默认时间
timeTemp=`date +%T`
dateTemp=`date +%F`
date="${dateTemp} ${timeTemp}"

# 不是新创建的读bak文件
if [ "${isnew}" != "true" ]; then
    dateTemp=`awk '/date/ {printf("%s %s\n",$2,$3)}' ./posts/${filename}.bak | head -n 1`;
    echo "read date from bak file, date: ${dateTemp}"
    # 读到的日期不为空 替换掉当前时间
    if [ -n "${dateTemp}" ] ; then
        date="${dateTemp}"
    fi
    categories=`awk '/categories/ {printf("%s\n",$2)}' ./posts/${filename}.bak | head -n 1`;
    tags=`awk '/tags/ {printf("%s\n",$2)}' ./posts/${filename}.bak | head -n 1`;
fi

# 使用输入的分类标签
if [ $# -ge 2 ]; then
    categories=${2}
fi
if [ $# -ge 3 ]; then
    tags=${3}
fi

# 删除第一个---号之前的所有行
sed -i '1,/---/d' ${filePath}

# 替换第一个## 前面的行里面的---
sed -i '1,/##/s/---/<!--more-->/' ${filePath}

# 替换插入
echo "head info:"
echo "title: ${title}"
echo "date: ${date}"
echo "tags: ${tags}"
echo "categories: ${categories}"

sed -i '1i---' ${filePath}
sed -i "1icategories: ${categories}" ${filePath}
sed -i "1itags: ${tags}" ${filePath}
sed -i "1idate: ${date} ${time}" ${filePath}
sed -i "1ititle: ${title}" ${filePath}
sed -i '1i---' ${filePath}

# 去掉行尾的
sed -i 's///' ${filePath}

# 修改后的文件覆盖自动生成的文件
echo "copy to source ..."
cp ${filePath} ./source/_posts/${filename}.md
# 将修改后的文件存为bak
echo "move to ${filename}.bak ..."
mv ${filePath} ./posts/${filename}.bak
echo "done"
